Note
Click here to download the full example code
DCGAN Tutorial¶
Author: Nathan Inkawhich
Introduction¶
This tutorial will give an introduction to DCGANs through an example. We will train a generative adversarial network (GAN) to generate new celebrities after showing it pictures of many real celebrities. Most of the code here is from the dcgan implementation in pytorch/examples, and this document will give a thorough explanation of the implementation and shed light on how and why this model works. But don’t worry, no prior knowledge of GANs is required, but it may require a first-timer to spend some time reasoning about what is actually happening under the hood. Also, for the sake of time it will help to have a GPU, or two. Lets start from the beginning.
Generative Adversarial Networks¶
What is a GAN?¶
GANs are a framework for teaching a DL model to capture the training data’s distribution so we can generate new data from that same distribution. GANs were invented by Ian Goodfellow in 2014 and first described in the paper Generative Adversarial Nets. They are made of two distinct models, a generator and a discriminator. The job of the generator is to spawn ‘fake’ images that look like the training images. The job of the discriminator is to look at an image and output whether or not it is a real training image or a fake image from the generator. During training, the generator is constantly trying to outsmart the discriminator by generating better and better fakes, while the discriminator is working to become a better detective and correctly classify the real and fake images. The equilibrium of this game is when the generator is generating perfect fakes that look as if they came directly from the training data, and the discriminator is left to always guess at 50% confidence that the generator output is real or fake.
Now, lets define some notation to be used throughout tutorial starting with the discriminator. Let \(x\) be data representing an image. \(D(x)\) is the discriminator network which outputs the (scalar) probability that \(x\) came from training data rather than the generator. Here, since we are dealing with images, the input to \(D(x)\) is an image of CHW size 3x64x64. Intuitively, \(D(x)\) should be HIGH when \(x\) comes from training data and LOW when \(x\) comes from the generator. \(D(x)\) can also be thought of as a traditional binary classifier.
For the generator’s notation, let \(z\) be a latent space vector sampled from a standard normal distribution. \(G(z)\) represents the generator function which maps the latent vector \(z\) to data-space. The goal of \(G\) is to estimate the distribution that the training data comes from (\(p_{data}\)) so it can generate fake samples from that estimated distribution (\(p_g\)).
So, \(D(G(z))\) is the probability (scalar) that the output of the generator \(G\) is a real image. As described in Goodfellow’s paper, \(D\) and \(G\) play a minimax game in which \(D\) tries to maximize the probability it correctly classifies reals and fakes (\(logD(x)\)), and \(G\) tries to minimize the probability that \(D\) will predict its outputs are fake (\(log(1-D(G(z)))\)). From the paper, the GAN loss function is
In theory, the solution to this minimax game is where \(p_g = p_{data}\), and the discriminator guesses randomly if the inputs are real or fake. However, the convergence theory of GANs is still being actively researched and in reality models do not always train to this point.
What is a DCGAN?¶
A DCGAN is a direct extension of the GAN described above, except that it explicitly uses convolutional and convolutional-transpose layers in the discriminator and generator, respectively. It was first described by Radford et. al. in the paper Unsupervised Representation Learning With Deep Convolutional Generative Adversarial Networks. The discriminator is made up of strided convolution layers, batch norm layers, and LeakyReLU activations. The input is a 3x64x64 input image and the output is a scalar probability that the input is from the real data distribution. The generator is comprised of convolutional-transpose layers, batch norm layers, and ReLU activations. The input is a latent vector, \(z\), that is drawn from a standard normal distribution and the output is a 3x64x64 RGB image. The strided conv-transpose layers allow the latent vector to be transformed into a volume with the same shape as an image. In the paper, the authors also give some tips about how to setup the optimizers, how to calculate the loss functions, and how to initialize the model weights, all of which will be explained in the coming sections.
from __future__ import print_function
#%matplotlib inline
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.utils as vutils
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from IPython.display import HTML
# Set random seed for reproducibility
manualSeed = 999
#manualSeed = random.randint(1, 10000) # use if you want new results
print("Random Seed: ", manualSeed)
random.seed(manualSeed)
torch.manual_seed(manualSeed)
Random Seed: 999
<torch._C.Generator object at 0x7faf96bd4b30>
Inputs¶
Let’s define some inputs for the run:
dataroot - the path to the root of the dataset folder. We will talk more about the dataset in the next section
workers - the number of worker threads for loading the data with the DataLoader
batch_size - the batch size used in training. The DCGAN paper uses a batch size of 128
image_size - the spatial size of the images used for training. This implementation defaults to 64x64. If another size is desired, the structures of D and G must be changed. See here for more details
nc - number of color channels in the input images. For color images this is 3
nz - length of latent vector
ngf - relates to the depth of feature maps carried through the generator
ndf - sets the depth of feature maps propagated through the discriminator
num_epochs - number of training epochs to run. Training for longer will probably lead to better results but will also take much longer
lr - learning rate for training. As described in the DCGAN paper, this number should be 0.0002
beta1 - beta1 hyperparameter for Adam optimizers. As described in paper, this number should be 0.5
ngpu - number of GPUs available. If this is 0, code will run in CPU mode. If this number is greater than 0 it will run on that number of GPUs
# Root directory for dataset
dataroot = "data/celeba"
# Number of workers for dataloader
workers = 2
# Batch size during training
batch_size = 128
# Spatial size of training images. All images will be resized to this
# size using a transformer.
image_size = 64
# Number of channels in the training images. For color images this is 3
nc = 3
# Size of z latent vector (i.e. size of generator input)
nz = 100
# Size of feature maps in generator
ngf = 64
# Size of feature maps in discriminator
ndf = 64
# Number of training epochs
num_epochs = 5
# Learning rate for optimizers
lr = 0.0002
# Beta1 hyperparam for Adam optimizers
beta1 = 0.5
# Number of GPUs available. Use 0 for CPU mode.
ngpu = 1
Data¶
In this tutorial we will use the Celeb-A Faces dataset which can be downloaded at the linked site, or in Google Drive. The dataset will download as a file named img_align_celeba.zip. Once downloaded, create a directory named celeba and extract the zip file into that directory. Then, set the dataroot input for this notebook to the celeba directory you just created. The resulting directory structure should be:
/path/to/celeba
-> img_align_celeba
-> 188242.jpg
-> 173822.jpg
-> 284702.jpg
-> 537394.jpg
...
This is an important step because we will be using the ImageFolder dataset class, which requires there to be subdirectories in the dataset’s root folder. Now, we can create the dataset, create the dataloader, set the device to run on, and finally visualize some of the training data.
# We can use an image folder dataset the way we have it setup.
# Create the dataset
dataset = dset.ImageFolder(root=dataroot,
transform=transforms.Compose([
transforms.Resize(image_size),
transforms.CenterCrop(image_size),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
]))
# Create the dataloader
dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size,
shuffle=True, num_workers=workers)
# Decide which device we want to run on
device = torch.device("cuda:0" if (torch.cuda.is_available() and ngpu > 0) else "cpu")
# Plot some training images
real_batch = next(iter(dataloader))
plt.figure(figsize=(8,8))
plt.axis("off")
plt.title("Training Images")
plt.imshow(np.transpose(vutils.make_grid(real_batch[0].to(device)[:64], padding=2, normalize=True).cpu(),(1,2,0)))

<matplotlib.image.AxesImage object at 0x7faf63a6ed10>
Implementation¶
With our input parameters set and the dataset prepared, we can now get into the implementation. We will start with the weight initialization strategy, then talk about the generator, discriminator, loss functions, and training loop in detail.
Weight Initialization¶
From the DCGAN paper, the authors specify that all model weights shall
be randomly initialized from a Normal distribution with mean=0,
stdev=0.02. The weights_init function takes an initialized model as
input and reinitializes all convolutional, convolutional-transpose, and
batch normalization layers to meet this criteria. This function is
applied to the models immediately after initialization.
# custom weights initialization called on netG and netD
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
nn.init.normal_(m.weight.data, 0.0, 0.02)
elif classname.find('BatchNorm') != -1:
nn.init.normal_(m.weight.data, 1.0, 0.02)
nn.init.constant_(m.bias.data, 0)
Generator¶
The generator, \(G\), is designed to map the latent space vector (\(z\)) to data-space. Since our data are images, converting \(z\) to data-space means ultimately creating a RGB image with the same size as the training images (i.e. 3x64x64). In practice, this is accomplished through a series of strided two dimensional convolutional transpose layers, each paired with a 2d batch norm layer and a relu activation. The output of the generator is fed through a tanh function to return it to the input data range of \([-1,1]\). It is worth noting the existence of the batch norm functions after the conv-transpose layers, as this is a critical contribution of the DCGAN paper. These layers help with the flow of gradients during training. An image of the generator from the DCGAN paper is shown below.
Notice, how the inputs we set in the input section (nz, ngf, and nc) influence the generator architecture in code. nz is the length of the z input vector, ngf relates to the size of the feature maps that are propagated through the generator, and nc is the number of channels in the output image (set to 3 for RGB images). Below is the code for the generator.
# Generator Code
class Generator(nn.Module):
def __init__(self, ngpu):
super(Generator, self).__init__()
self.ngpu = ngpu
self.main = nn.Sequential(
# input is Z, going into a convolution
nn.ConvTranspose2d( nz, ngf * 8, 4, 1, 0, bias=False),
nn.BatchNorm2d(ngf * 8),
nn.ReLU(True),
# state size. (ngf*8) x 4 x 4
nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1, bias=False),
nn.BatchNorm2d(ngf * 4),
nn.ReLU(True),
# state size. (ngf*4) x 8 x 8
nn.ConvTranspose2d( ngf * 4, ngf * 2, 4, 2, 1, bias=False),
nn.BatchNorm2d(ngf * 2),
nn.ReLU(True),
# state size. (ngf*2) x 16 x 16
nn.ConvTranspose2d( ngf * 2, ngf, 4, 2, 1, bias=False),
nn.BatchNorm2d(ngf),
nn.ReLU(True),
# state size. (ngf) x 32 x 32
nn.ConvTranspose2d( ngf, nc, 4, 2, 1, bias=False),
nn.Tanh()
# state size. (nc) x 64 x 64
)
def forward(self, input):
return self.main(input)
Now, we can instantiate the generator and apply the weights_init
function. Check out the printed model to see how the generator object is
structured.
# Create the generator
netG = Generator(ngpu).to(device)
# Handle multi-gpu if desired
if (device.type == 'cuda') and (ngpu > 1):
netG = nn.DataParallel(netG, list(range(ngpu)))
# Apply the weights_init function to randomly initialize all weights
# to mean=0, stdev=0.02.
netG.apply(weights_init)
# Print the model
print(netG)
Generator(
(main): Sequential(
(0): ConvTranspose2d(100, 512, kernel_size=(4, 4), stride=(1, 1), bias=False)
(1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(2): ReLU(inplace=True)
(3): ConvTranspose2d(512, 256, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(4): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(5): ReLU(inplace=True)
(6): ConvTranspose2d(256, 128, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(7): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(8): ReLU(inplace=True)
(9): ConvTranspose2d(128, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(10): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(11): ReLU(inplace=True)
(12): ConvTranspose2d(64, 3, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(13): Tanh()
)
)
Discriminator¶
As mentioned, the discriminator, \(D\), is a binary classification network that takes an image as input and outputs a scalar probability that the input image is real (as opposed to fake). Here, \(D\) takes a 3x64x64 input image, processes it through a series of Conv2d, BatchNorm2d, and LeakyReLU layers, and outputs the final probability through a Sigmoid activation function. This architecture can be extended with more layers if necessary for the problem, but there is significance to the use of the strided convolution, BatchNorm, and LeakyReLUs. The DCGAN paper mentions it is a good practice to use strided convolution rather than pooling to downsample because it lets the network learn its own pooling function. Also batch norm and leaky relu functions promote healthy gradient flow which is critical for the learning process of both \(G\) and \(D\).
Discriminator Code
class Discriminator(nn.Module):
def __init__(self, ngpu):
super(Discriminator, self).__init__()
self.ngpu = ngpu
self.main = nn.Sequential(
# input is (nc) x 64 x 64
nn.Conv2d(nc, ndf, 4, 2, 1, bias=False),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ndf) x 32 x 32
nn.Conv2d(ndf, ndf * 2, 4, 2, 1, bias=False),
nn.BatchNorm2d(ndf * 2),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ndf*2) x 16 x 16
nn.Conv2d(ndf * 2, ndf * 4, 4, 2, 1, bias=False),
nn.BatchNorm2d(ndf * 4),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ndf*4) x 8 x 8
nn.Conv2d(ndf * 4, ndf * 8, 4, 2, 1, bias=False),
nn.BatchNorm2d(ndf * 8),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ndf*8) x 4 x 4
nn.Conv2d(ndf * 8, 1, 4, 1, 0, bias=False),
nn.Sigmoid()
)
def forward(self, input):
return self.main(input)
Now, as with the generator, we can create the discriminator, apply the
weights_init function, and print the model’s structure.
# Create the Discriminator
netD = Discriminator(ngpu).to(device)
# Handle multi-gpu if desired
if (device.type == 'cuda') and (ngpu > 1):
netD = nn.DataParallel(netD, list(range(ngpu)))
# Apply the weights_init function to randomly initialize all weights
# to mean=0, stdev=0.2.
netD.apply(weights_init)
# Print the model
print(netD)
Discriminator(
(main): Sequential(
(0): Conv2d(3, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(1): LeakyReLU(negative_slope=0.2, inplace=True)
(2): Conv2d(64, 128, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(3): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(4): LeakyReLU(negative_slope=0.2, inplace=True)
(5): Conv2d(128, 256, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(6): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(7): LeakyReLU(negative_slope=0.2, inplace=True)
(8): Conv2d(256, 512, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(9): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(10): LeakyReLU(negative_slope=0.2, inplace=True)
(11): Conv2d(512, 1, kernel_size=(4, 4), stride=(1, 1), bias=False)
(12): Sigmoid()
)
)
Loss Functions and Optimizers¶
With \(D\) and \(G\) setup, we can specify how they learn through the loss functions and optimizers. We will use the Binary Cross Entropy loss (BCELoss) function which is defined in PyTorch as:
Notice how this function provides the calculation of both log components in the objective function (i.e. \(log(D(x))\) and \(log(1-D(G(z)))\)). We can specify what part of the BCE equation to use with the \(y\) input. This is accomplished in the training loop which is coming up soon, but it is important to understand how we can choose which component we wish to calculate just by changing \(y\) (i.e. GT labels).
Next, we define our real label as 1 and the fake label as 0. These labels will be used when calculating the losses of \(D\) and \(G\), and this is also the convention used in the original GAN paper. Finally, we set up two separate optimizers, one for \(D\) and one for \(G\). As specified in the DCGAN paper, both are Adam optimizers with learning rate 0.0002 and Beta1 = 0.5. For keeping track of the generator’s learning progression, we will generate a fixed batch of latent vectors that are drawn from a Gaussian distribution (i.e. fixed_noise) . In the training loop, we will periodically input this fixed_noise into \(G\), and over the iterations we will see images form out of the noise.
# Initialize BCELoss function
criterion = nn.BCELoss()
# Create batch of latent vectors that we will use to visualize
# the progression of the generator
fixed_noise = torch.randn(64, nz, 1, 1, device=device)
# Establish convention for real and fake labels during training
real_label = 1.
fake_label = 0.
# Setup Adam optimizers for both G and D
optimizerD = optim.Adam(netD.parameters(), lr=lr, betas=(beta1, 0.999))
optimizerG = optim.Adam(netG.parameters(), lr=lr, betas=(beta1, 0.999))
Training¶
Finally, now that we have all of the parts of the GAN framework defined, we can train it. Be mindful that training GANs is somewhat of an art form, as incorrect hyperparameter settings lead to mode collapse with little explanation of what went wrong. Here, we will closely follow Algorithm 1 from Goodfellow’s paper, while abiding by some of the best practices shown in ganhacks. Namely, we will “construct different mini-batches for real and fake” images, and also adjust G’s objective function to maximize \(logD(G(z))\). Training is split up into two main parts. Part 1 updates the Discriminator and Part 2 updates the Generator.
Part 1 - Train the Discriminator
Recall, the goal of training the discriminator is to maximize the probability of correctly classifying a given input as real or fake. In terms of Goodfellow, we wish to “update the discriminator by ascending its stochastic gradient”. Practically, we want to maximize \(log(D(x)) + log(1-D(G(z)))\). Due to the separate mini-batch suggestion from ganhacks, we will calculate this in two steps. First, we will construct a batch of real samples from the training set, forward pass through \(D\), calculate the loss (\(log(D(x))\)), then calculate the gradients in a backward pass. Secondly, we will construct a batch of fake samples with the current generator, forward pass this batch through \(D\), calculate the loss (\(log(1-D(G(z)))\)), and accumulate the gradients with a backward pass. Now, with the gradients accumulated from both the all-real and all-fake batches, we call a step of the Discriminator’s optimizer.
Part 2 - Train the Generator
As stated in the original paper, we want to train the Generator by minimizing \(log(1-D(G(z)))\) in an effort to generate better fakes. As mentioned, this was shown by Goodfellow to not provide sufficient gradients, especially early in the learning process. As a fix, we instead wish to maximize \(log(D(G(z)))\). In the code we accomplish this by: classifying the Generator output from Part 1 with the Discriminator, computing G’s loss using real labels as GT, computing G’s gradients in a backward pass, and finally updating G’s parameters with an optimizer step. It may seem counter-intuitive to use the real labels as GT labels for the loss function, but this allows us to use the \(log(x)\) part of the BCELoss (rather than the \(log(1-x)\) part) which is exactly what we want.
Finally, we will do some statistic reporting and at the end of each epoch we will push our fixed_noise batch through the generator to visually track the progress of G’s training. The training statistics reported are:
Loss_D - discriminator loss calculated as the sum of losses for the all real and all fake batches (\(log(D(x)) + log(1 - D(G(z)))\)).
Loss_G - generator loss calculated as \(log(D(G(z)))\)
D(x) - the average output (across the batch) of the discriminator for the all real batch. This should start close to 1 then theoretically converge to 0.5 when G gets better. Think about why this is.
D(G(z)) - average discriminator outputs for the all fake batch. The first number is before D is updated and the second number is after D is updated. These numbers should start near 0 and converge to 0.5 as G gets better. Think about why this is.
Note: This step might take a while, depending on how many epochs you run and if you removed some data from the dataset.
# Training Loop
# Lists to keep track of progress
img_list = []
G_losses = []
D_losses = []
iters = 0
print("Starting Training Loop...")
# For each epoch
for epoch in range(num_epochs):
# For each batch in the dataloader
for i, data in enumerate(dataloader, 0):
############################
# (1) Update D network: maximize log(D(x)) + log(1 - D(G(z)))
###########################
## Train with all-real batch
netD.zero_grad()
# Format batch
real_cpu = data[0].to(device)
b_size = real_cpu.size(0)
label = torch.full((b_size,), real_label, dtype=torch.float, device=device)
# Forward pass real batch through D
output = netD(real_cpu).view(-1)
# Calculate loss on all-real batch
errD_real = criterion(output, label)
# Calculate gradients for D in backward pass
errD_real.backward()
D_x = output.mean().item()
## Train with all-fake batch
# Generate batch of latent vectors
noise = torch.randn(b_size, nz, 1, 1, device=device)
# Generate fake image batch with G
fake = netG(noise)
label.fill_(fake_label)
# Classify all fake batch with D
output = netD(fake.detach()).view(-1)
# Calculate D's loss on the all-fake batch
errD_fake = criterion(output, label)
# Calculate the gradients for this batch, accumulated (summed) with previous gradients
errD_fake.backward()
D_G_z1 = output.mean().item()
# Compute error of D as sum over the fake and the real batches
errD = errD_real + errD_fake
# Update D
optimizerD.step()
############################
# (2) Update G network: maximize log(D(G(z)))
###########################
netG.zero_grad()
label.fill_(real_label) # fake labels are real for generator cost
# Since we just updated D, perform another forward pass of all-fake batch through D
output = netD(fake).view(-1)
# Calculate G's loss based on this output
errG = criterion(output, label)
# Calculate gradients for G
errG.backward()
D_G_z2 = output.mean().item()
# Update G
optimizerG.step()
# Output training stats
if i % 50 == 0:
print('[%d/%d][%d/%d]\tLoss_D: %.4f\tLoss_G: %.4f\tD(x): %.4f\tD(G(z)): %.4f / %.4f'
% (epoch, num_epochs, i, len(dataloader),
errD.item(), errG.item(), D_x, D_G_z1, D_G_z2))
# Save Losses for plotting later
G_losses.append(errG.item())
D_losses.append(errD.item())
# Check how the generator is doing by saving G's output on fixed_noise
if (iters % 500 == 0) or ((epoch == num_epochs-1) and (i == len(dataloader)-1)):
with torch.no_grad():
fake = netG(fixed_noise).detach().cpu()
img_list.append(vutils.make_grid(fake, padding=2, normalize=True))
iters += 1
Starting Training Loop...
[0/5][0/1583] Loss_D: 1.6264 Loss_G: 5.5240 D(x): 0.5733 D(G(z)): 0.5501 / 0.0065
[0/5][50/1583] Loss_D: 0.0762 Loss_G: 10.0336 D(x): 0.9534 D(G(z)): 0.0009 / 0.0001
[0/5][100/1583] Loss_D: 0.9860 Loss_G: 15.0782 D(x): 0.9761 D(G(z)): 0.4853 / 0.0000
[0/5][150/1583] Loss_D: 0.8306 Loss_G: 9.0195 D(x): 0.9748 D(G(z)): 0.4862 / 0.0005
[0/5][200/1583] Loss_D: 0.9747 Loss_G: 10.1259 D(x): 0.9665 D(G(z)): 0.5223 / 0.0002
[0/5][250/1583] Loss_D: 0.4945 Loss_G: 4.6251 D(x): 0.8134 D(G(z)): 0.0930 / 0.0186
[0/5][300/1583] Loss_D: 1.8190 Loss_G: 4.2330 D(x): 0.3154 D(G(z)): 0.0063 / 0.0423
[0/5][350/1583] Loss_D: 0.4060 Loss_G: 4.4574 D(x): 0.9253 D(G(z)): 0.2088 / 0.0327
[0/5][400/1583] Loss_D: 0.4100 Loss_G: 4.2699 D(x): 0.7706 D(G(z)): 0.0498 / 0.0278
[0/5][450/1583] Loss_D: 0.5403 Loss_G: 3.7834 D(x): 0.7591 D(G(z)): 0.1147 / 0.0410
[0/5][500/1583] Loss_D: 0.4008 Loss_G: 3.5969 D(x): 0.8396 D(G(z)): 0.1612 / 0.0436
[0/5][550/1583] Loss_D: 0.3453 Loss_G: 3.7227 D(x): 0.8366 D(G(z)): 0.0929 / 0.0465
[0/5][600/1583] Loss_D: 0.3367 Loss_G: 8.5563 D(x): 0.7844 D(G(z)): 0.0020 / 0.0022
[0/5][650/1583] Loss_D: 0.9395 Loss_G: 7.0406 D(x): 0.8458 D(G(z)): 0.4493 / 0.0022
[0/5][700/1583] Loss_D: 0.2453 Loss_G: 4.2413 D(x): 0.8780 D(G(z)): 0.0845 / 0.0218
[0/5][750/1583] Loss_D: 0.4236 Loss_G: 5.1704 D(x): 0.8784 D(G(z)): 0.1931 / 0.0132
[0/5][800/1583] Loss_D: 0.2143 Loss_G: 5.6545 D(x): 0.8683 D(G(z)): 0.0436 / 0.0085
[0/5][850/1583] Loss_D: 0.2903 Loss_G: 4.4755 D(x): 0.8981 D(G(z)): 0.1406 / 0.0199
[0/5][900/1583] Loss_D: 1.2898 Loss_G: 9.3056 D(x): 0.9494 D(G(z)): 0.6309 / 0.0003
[0/5][950/1583] Loss_D: 0.6580 Loss_G: 4.6007 D(x): 0.8018 D(G(z)): 0.2872 / 0.0178
[0/5][1000/1583] Loss_D: 0.4199 Loss_G: 4.2365 D(x): 0.7412 D(G(z)): 0.0490 / 0.0275
[0/5][1050/1583] Loss_D: 0.3416 Loss_G: 3.5613 D(x): 0.8255 D(G(z)): 0.1045 / 0.0510
[0/5][1100/1583] Loss_D: 0.5089 Loss_G: 5.1600 D(x): 0.9195 D(G(z)): 0.2814 / 0.0102
[0/5][1150/1583] Loss_D: 0.2946 Loss_G: 4.3554 D(x): 0.8322 D(G(z)): 0.0595 / 0.0247
[0/5][1200/1583] Loss_D: 0.6836 Loss_G: 2.4835 D(x): 0.6533 D(G(z)): 0.0975 / 0.1226
[0/5][1250/1583] Loss_D: 0.5359 Loss_G: 3.1393 D(x): 0.7081 D(G(z)): 0.0563 / 0.0856
[0/5][1300/1583] Loss_D: 0.5798 Loss_G: 6.9091 D(x): 0.9317 D(G(z)): 0.3514 / 0.0021
[0/5][1350/1583] Loss_D: 0.4096 Loss_G: 4.0011 D(x): 0.8446 D(G(z)): 0.1703 / 0.0364
[0/5][1400/1583] Loss_D: 0.7236 Loss_G: 5.8381 D(x): 0.8431 D(G(z)): 0.3464 / 0.0057
[0/5][1450/1583] Loss_D: 1.0746 Loss_G: 1.7810 D(x): 0.4683 D(G(z)): 0.0460 / 0.2271
[0/5][1500/1583] Loss_D: 0.4479 Loss_G: 4.5207 D(x): 0.8893 D(G(z)): 0.2298 / 0.0190
[0/5][1550/1583] Loss_D: 0.6665 Loss_G: 3.6238 D(x): 0.9110 D(G(z)): 0.3690 / 0.0464
[1/5][0/1583] Loss_D: 0.5210 Loss_G: 4.8103 D(x): 0.9486 D(G(z)): 0.3221 / 0.0142
[1/5][50/1583] Loss_D: 0.6958 Loss_G: 3.5716 D(x): 0.7543 D(G(z)): 0.2761 / 0.0408
[1/5][100/1583] Loss_D: 0.8117 Loss_G: 1.2783 D(x): 0.5261 D(G(z)): 0.0263 / 0.3623
[1/5][150/1583] Loss_D: 1.6475 Loss_G: 4.9782 D(x): 0.3079 D(G(z)): 0.0004 / 0.0232
[1/5][200/1583] Loss_D: 0.4474 Loss_G: 2.6884 D(x): 0.7950 D(G(z)): 0.1464 / 0.0955
[1/5][250/1583] Loss_D: 0.7453 Loss_G: 2.2962 D(x): 0.5924 D(G(z)): 0.0436 / 0.1514
[1/5][300/1583] Loss_D: 0.6230 Loss_G: 3.4745 D(x): 0.9151 D(G(z)): 0.3474 / 0.0578
[1/5][350/1583] Loss_D: 0.5018 Loss_G: 5.0521 D(x): 0.8796 D(G(z)): 0.2739 / 0.0099
[1/5][400/1583] Loss_D: 0.4320 Loss_G: 4.2411 D(x): 0.8667 D(G(z)): 0.2133 / 0.0239
[1/5][450/1583] Loss_D: 0.3843 Loss_G: 3.4227 D(x): 0.7833 D(G(z)): 0.0879 / 0.0636
[1/5][500/1583] Loss_D: 4.1799 Loss_G: 1.6103 D(x): 0.0413 D(G(z)): 0.0042 / 0.2811
[1/5][550/1583] Loss_D: 0.3480 Loss_G: 3.4176 D(x): 0.8033 D(G(z)): 0.0917 / 0.0433
[1/5][600/1583] Loss_D: 1.7355 Loss_G: 1.1664 D(x): 0.2682 D(G(z)): 0.0015 / 0.3996
[1/5][650/1583] Loss_D: 1.0287 Loss_G: 8.4783 D(x): 0.9696 D(G(z)): 0.5634 / 0.0006
[1/5][700/1583] Loss_D: 0.2762 Loss_G: 3.4489 D(x): 0.9036 D(G(z)): 0.1434 / 0.0472
[1/5][750/1583] Loss_D: 1.4888 Loss_G: 0.5156 D(x): 0.3697 D(G(z)): 0.1452 / 0.6568
[1/5][800/1583] Loss_D: 0.3663 Loss_G: 3.8022 D(x): 0.8738 D(G(z)): 0.1874 / 0.0329
[1/5][850/1583] Loss_D: 0.3517 Loss_G: 2.3898 D(x): 0.8065 D(G(z)): 0.0874 / 0.1222
[1/5][900/1583] Loss_D: 0.9078 Loss_G: 5.4656 D(x): 0.9068 D(G(z)): 0.5091 / 0.0082
[1/5][950/1583] Loss_D: 0.8656 Loss_G: 6.2798 D(x): 0.9431 D(G(z)): 0.4978 / 0.0032
[1/5][1000/1583] Loss_D: 1.1518 Loss_G: 5.4466 D(x): 0.9758 D(G(z)): 0.6159 / 0.0080
[1/5][1050/1583] Loss_D: 0.4323 Loss_G: 3.0846 D(x): 0.8315 D(G(z)): 0.1848 / 0.0646
[1/5][1100/1583] Loss_D: 0.6565 Loss_G: 4.1123 D(x): 0.9234 D(G(z)): 0.3940 / 0.0260
[1/5][1150/1583] Loss_D: 1.1437 Loss_G: 5.7734 D(x): 0.9720 D(G(z)): 0.6035 / 0.0074
[1/5][1200/1583] Loss_D: 0.5371 Loss_G: 4.2498 D(x): 0.8785 D(G(z)): 0.2935 / 0.0222
[1/5][1250/1583] Loss_D: 0.8962 Loss_G: 2.9604 D(x): 0.6807 D(G(z)): 0.2956 / 0.0830
[1/5][1300/1583] Loss_D: 0.5995 Loss_G: 2.7504 D(x): 0.7879 D(G(z)): 0.2590 / 0.0879
[1/5][1350/1583] Loss_D: 0.6228 Loss_G: 2.0498 D(x): 0.6476 D(G(z)): 0.0882 / 0.1624
[1/5][1400/1583] Loss_D: 0.4111 Loss_G: 2.8745 D(x): 0.7986 D(G(z)): 0.1416 / 0.0852
[1/5][1450/1583] Loss_D: 0.4333 Loss_G: 2.7808 D(x): 0.7601 D(G(z)): 0.0928 / 0.0832
[1/5][1500/1583] Loss_D: 0.4775 Loss_G: 2.2005 D(x): 0.7739 D(G(z)): 0.1454 / 0.1483
[1/5][1550/1583] Loss_D: 0.6787 Loss_G: 3.4091 D(x): 0.8056 D(G(z)): 0.3135 / 0.0450
[2/5][0/1583] Loss_D: 0.6084 Loss_G: 2.2235 D(x): 0.6401 D(G(z)): 0.0599 / 0.1535
[2/5][50/1583] Loss_D: 0.8070 Loss_G: 3.9927 D(x): 0.9383 D(G(z)): 0.4764 / 0.0294
[2/5][100/1583] Loss_D: 0.6170 Loss_G: 3.9837 D(x): 0.8788 D(G(z)): 0.3436 / 0.0284
[2/5][150/1583] Loss_D: 3.0823 Loss_G: 1.5920 D(x): 0.1369 D(G(z)): 0.0156 / 0.3129
[2/5][200/1583] Loss_D: 0.9600 Loss_G: 0.9955 D(x): 0.4665 D(G(z)): 0.0411 / 0.4308
[2/5][250/1583] Loss_D: 1.0931 Loss_G: 4.9392 D(x): 0.9853 D(G(z)): 0.5983 / 0.0128
[2/5][300/1583] Loss_D: 0.5980 Loss_G: 2.9624 D(x): 0.8185 D(G(z)): 0.2949 / 0.0644
[2/5][350/1583] Loss_D: 1.1148 Loss_G: 6.1380 D(x): 0.9325 D(G(z)): 0.5873 / 0.0052
[2/5][400/1583] Loss_D: 0.8607 Loss_G: 3.5920 D(x): 0.9018 D(G(z)): 0.4670 / 0.0408
[2/5][450/1583] Loss_D: 1.3886 Loss_G: 1.5800 D(x): 0.3455 D(G(z)): 0.0564 / 0.3031
[2/5][500/1583] Loss_D: 0.5267 Loss_G: 2.1352 D(x): 0.7059 D(G(z)): 0.1015 / 0.1593
[2/5][550/1583] Loss_D: 0.7662 Loss_G: 1.8600 D(x): 0.5546 D(G(z)): 0.0555 / 0.2321
[2/5][600/1583] Loss_D: 0.9141 Loss_G: 3.4755 D(x): 0.7931 D(G(z)): 0.4295 / 0.0465
[2/5][650/1583] Loss_D: 0.6842 Loss_G: 1.3442 D(x): 0.6451 D(G(z)): 0.1592 / 0.3050
[2/5][700/1583] Loss_D: 0.4560 Loss_G: 2.4794 D(x): 0.7965 D(G(z)): 0.1752 / 0.1107
[2/5][750/1583] Loss_D: 0.8479 Loss_G: 3.4265 D(x): 0.8454 D(G(z)): 0.4413 / 0.0480
[2/5][800/1583] Loss_D: 0.4924 Loss_G: 3.2555 D(x): 0.8223 D(G(z)): 0.2205 / 0.0540
[2/5][850/1583] Loss_D: 0.5915 Loss_G: 3.2648 D(x): 0.8339 D(G(z)): 0.3053 / 0.0539
[2/5][900/1583] Loss_D: 0.5457 Loss_G: 2.6938 D(x): 0.7867 D(G(z)): 0.2308 / 0.0994
[2/5][950/1583] Loss_D: 1.2933 Loss_G: 0.1015 D(x): 0.3535 D(G(z)): 0.0357 / 0.9125
[2/5][1000/1583] Loss_D: 0.5324 Loss_G: 1.9934 D(x): 0.7311 D(G(z)): 0.1644 / 0.1685
[2/5][1050/1583] Loss_D: 0.5709 Loss_G: 2.9711 D(x): 0.8514 D(G(z)): 0.3015 / 0.0687
[2/5][1100/1583] Loss_D: 0.5736 Loss_G: 3.0831 D(x): 0.8757 D(G(z)): 0.3239 / 0.0604
[2/5][1150/1583] Loss_D: 1.1736 Loss_G: 1.7116 D(x): 0.4194 D(G(z)): 0.0741 / 0.2440
[2/5][1200/1583] Loss_D: 0.4516 Loss_G: 2.9869 D(x): 0.8709 D(G(z)): 0.2441 / 0.0637
[2/5][1250/1583] Loss_D: 0.3669 Loss_G: 3.0568 D(x): 0.8292 D(G(z)): 0.1451 / 0.0648
[2/5][1300/1583] Loss_D: 0.5791 Loss_G: 2.3419 D(x): 0.7037 D(G(z)): 0.1541 / 0.1247
[2/5][1350/1583] Loss_D: 0.5594 Loss_G: 2.7939 D(x): 0.7983 D(G(z)): 0.2517 / 0.0779
[2/5][1400/1583] Loss_D: 0.8287 Loss_G: 1.5621 D(x): 0.5239 D(G(z)): 0.0627 / 0.2579
[2/5][1450/1583] Loss_D: 0.6463 Loss_G: 4.0034 D(x): 0.9173 D(G(z)): 0.3971 / 0.0240
[2/5][1500/1583] Loss_D: 0.9348 Loss_G: 4.4673 D(x): 0.9324 D(G(z)): 0.5223 / 0.0179
[2/5][1550/1583] Loss_D: 0.4506 Loss_G: 2.5223 D(x): 0.7750 D(G(z)): 0.1511 / 0.1037
[3/5][0/1583] Loss_D: 0.4562 Loss_G: 2.1765 D(x): 0.7592 D(G(z)): 0.1354 / 0.1384
[3/5][50/1583] Loss_D: 0.7290 Loss_G: 3.9173 D(x): 0.8685 D(G(z)): 0.4021 / 0.0275
[3/5][100/1583] Loss_D: 0.5978 Loss_G: 3.1496 D(x): 0.8145 D(G(z)): 0.2721 / 0.0587
[3/5][150/1583] Loss_D: 0.5014 Loss_G: 3.3012 D(x): 0.8417 D(G(z)): 0.2542 / 0.0516
[3/5][200/1583] Loss_D: 0.7056 Loss_G: 1.7370 D(x): 0.6615 D(G(z)): 0.1965 / 0.2200
[3/5][250/1583] Loss_D: 0.9255 Loss_G: 4.7846 D(x): 0.9329 D(G(z)): 0.5231 / 0.0120
[3/5][300/1583] Loss_D: 0.6017 Loss_G: 1.9976 D(x): 0.7501 D(G(z)): 0.2361 / 0.1705
[3/5][350/1583] Loss_D: 0.9393 Loss_G: 3.6312 D(x): 0.8991 D(G(z)): 0.5076 / 0.0405
[3/5][400/1583] Loss_D: 0.5065 Loss_G: 2.4717 D(x): 0.7387 D(G(z)): 0.1556 / 0.1152
[3/5][450/1583] Loss_D: 1.1260 Loss_G: 4.5132 D(x): 0.9362 D(G(z)): 0.6083 / 0.0160
[3/5][500/1583] Loss_D: 0.7837 Loss_G: 1.4729 D(x): 0.5793 D(G(z)): 0.1272 / 0.2729
[3/5][550/1583] Loss_D: 0.7818 Loss_G: 2.6575 D(x): 0.7902 D(G(z)): 0.3704 / 0.0926
[3/5][600/1583] Loss_D: 0.4873 Loss_G: 3.0570 D(x): 0.7966 D(G(z)): 0.1958 / 0.0674
[3/5][650/1583] Loss_D: 1.0902 Loss_G: 1.2643 D(x): 0.4563 D(G(z)): 0.1370 / 0.3438
[3/5][700/1583] Loss_D: 0.5748 Loss_G: 1.9703 D(x): 0.7002 D(G(z)): 0.1428 / 0.1795
[3/5][750/1583] Loss_D: 0.6554 Loss_G: 3.8678 D(x): 0.9064 D(G(z)): 0.3847 / 0.0289
[3/5][800/1583] Loss_D: 0.7635 Loss_G: 1.0960 D(x): 0.5530 D(G(z)): 0.0781 / 0.3747
[3/5][850/1583] Loss_D: 0.9675 Loss_G: 4.3296 D(x): 0.9305 D(G(z)): 0.5243 / 0.0218
[3/5][900/1583] Loss_D: 0.6163 Loss_G: 3.6817 D(x): 0.8425 D(G(z)): 0.3207 / 0.0388
[3/5][950/1583] Loss_D: 0.8692 Loss_G: 1.7221 D(x): 0.4850 D(G(z)): 0.0366 / 0.2186
[3/5][1000/1583] Loss_D: 0.6694 Loss_G: 3.0500 D(x): 0.8199 D(G(z)): 0.3379 / 0.0631
[3/5][1050/1583] Loss_D: 0.7916 Loss_G: 0.9586 D(x): 0.5647 D(G(z)): 0.1350 / 0.4155
[3/5][1100/1583] Loss_D: 0.5670 Loss_G: 2.1753 D(x): 0.6707 D(G(z)): 0.0956 / 0.1500
[3/5][1150/1583] Loss_D: 0.7565 Loss_G: 1.1165 D(x): 0.5504 D(G(z)): 0.0677 / 0.3788
[3/5][1200/1583] Loss_D: 0.5640 Loss_G: 1.7353 D(x): 0.6862 D(G(z)): 0.1296 / 0.2158
[3/5][1250/1583] Loss_D: 0.6828 Loss_G: 1.9073 D(x): 0.5888 D(G(z)): 0.0783 / 0.1977
[3/5][1300/1583] Loss_D: 0.9472 Loss_G: 1.6989 D(x): 0.4686 D(G(z)): 0.0331 / 0.2512
[3/5][1350/1583] Loss_D: 0.7937 Loss_G: 1.2172 D(x): 0.5455 D(G(z)): 0.0937 / 0.3445
[3/5][1400/1583] Loss_D: 0.6974 Loss_G: 2.1273 D(x): 0.6998 D(G(z)): 0.2363 / 0.1504
[3/5][1450/1583] Loss_D: 0.6747 Loss_G: 2.7348 D(x): 0.7786 D(G(z)): 0.3040 / 0.0836
[3/5][1500/1583] Loss_D: 1.0628 Loss_G: 3.9712 D(x): 0.8834 D(G(z)): 0.5442 / 0.0291
[3/5][1550/1583] Loss_D: 0.5807 Loss_G: 2.3940 D(x): 0.8151 D(G(z)): 0.2800 / 0.1123
[4/5][0/1583] Loss_D: 0.6015 Loss_G: 3.0104 D(x): 0.8713 D(G(z)): 0.3350 / 0.0667
[4/5][50/1583] Loss_D: 3.4308 Loss_G: 2.4638 D(x): 0.8921 D(G(z)): 0.8435 / 0.1431
[4/5][100/1583] Loss_D: 0.6162 Loss_G: 1.8700 D(x): 0.6284 D(G(z)): 0.0828 / 0.1869
[4/5][150/1583] Loss_D: 0.6665 Loss_G: 1.5146 D(x): 0.6187 D(G(z)): 0.1049 / 0.2635
[4/5][200/1583] Loss_D: 0.5585 Loss_G: 2.2617 D(x): 0.7764 D(G(z)): 0.2153 / 0.1360
[4/5][250/1583] Loss_D: 0.8363 Loss_G: 3.1208 D(x): 0.8779 D(G(z)): 0.4483 / 0.0642
[4/5][300/1583] Loss_D: 0.7915 Loss_G: 3.9496 D(x): 0.8941 D(G(z)): 0.4534 / 0.0273
[4/5][350/1583] Loss_D: 0.6451 Loss_G: 1.6488 D(x): 0.6405 D(G(z)): 0.1246 / 0.2414
[4/5][400/1583] Loss_D: 0.5088 Loss_G: 3.2712 D(x): 0.8882 D(G(z)): 0.2898 / 0.0505
[4/5][450/1583] Loss_D: 1.1942 Loss_G: 1.0305 D(x): 0.3768 D(G(z)): 0.0307 / 0.4142
[4/5][500/1583] Loss_D: 0.7002 Loss_G: 2.1377 D(x): 0.6966 D(G(z)): 0.2352 / 0.1447
[4/5][550/1583] Loss_D: 0.6404 Loss_G: 3.9373 D(x): 0.9167 D(G(z)): 0.3829 / 0.0261
[4/5][600/1583] Loss_D: 0.6261 Loss_G: 2.4195 D(x): 0.7482 D(G(z)): 0.2435 / 0.1179
[4/5][650/1583] Loss_D: 1.8281 Loss_G: 0.7897 D(x): 0.2586 D(G(z)): 0.0870 / 0.5452
[4/5][700/1583] Loss_D: 0.5788 Loss_G: 2.1450 D(x): 0.7901 D(G(z)): 0.2547 / 0.1436
[4/5][750/1583] Loss_D: 0.6993 Loss_G: 1.7577 D(x): 0.6138 D(G(z)): 0.1106 / 0.2233
[4/5][800/1583] Loss_D: 0.5460 Loss_G: 1.8241 D(x): 0.6692 D(G(z)): 0.0930 / 0.1942
[4/5][850/1583] Loss_D: 0.8317 Loss_G: 1.8794 D(x): 0.6057 D(G(z)): 0.2099 / 0.1867
[4/5][900/1583] Loss_D: 0.5889 Loss_G: 3.1864 D(x): 0.8846 D(G(z)): 0.3420 / 0.0531
[4/5][950/1583] Loss_D: 0.6169 Loss_G: 2.0347 D(x): 0.7420 D(G(z)): 0.2321 / 0.1697
[4/5][1000/1583] Loss_D: 0.6792 Loss_G: 3.0485 D(x): 0.8902 D(G(z)): 0.3922 / 0.0657
[4/5][1050/1583] Loss_D: 0.5893 Loss_G: 3.2676 D(x): 0.8204 D(G(z)): 0.2900 / 0.0511
[4/5][1100/1583] Loss_D: 0.4970 Loss_G: 2.0010 D(x): 0.7687 D(G(z)): 0.1769 / 0.1656
[4/5][1150/1583] Loss_D: 1.2306 Loss_G: 5.1115 D(x): 0.9353 D(G(z)): 0.6429 / 0.0094
[4/5][1200/1583] Loss_D: 1.5663 Loss_G: 0.4089 D(x): 0.2775 D(G(z)): 0.0185 / 0.6930
[4/5][1250/1583] Loss_D: 0.7347 Loss_G: 2.2111 D(x): 0.6817 D(G(z)): 0.2383 / 0.1445
[4/5][1300/1583] Loss_D: 0.3798 Loss_G: 3.2746 D(x): 0.9000 D(G(z)): 0.2211 / 0.0499
[4/5][1350/1583] Loss_D: 1.0522 Loss_G: 2.6172 D(x): 0.7806 D(G(z)): 0.4667 / 0.0955
[4/5][1400/1583] Loss_D: 0.4806 Loss_G: 2.4129 D(x): 0.7947 D(G(z)): 0.1887 / 0.1133
[4/5][1450/1583] Loss_D: 0.6532 Loss_G: 2.8818 D(x): 0.8313 D(G(z)): 0.3317 / 0.0773
[4/5][1500/1583] Loss_D: 0.5152 Loss_G: 2.2856 D(x): 0.7255 D(G(z)): 0.1429 / 0.1270
[4/5][1550/1583] Loss_D: 1.3493 Loss_G: 0.7045 D(x): 0.3574 D(G(z)): 0.0799 / 0.5348
Results¶
Finally, lets check out how we did. Here, we will look at three different results. First, we will see how D and G’s losses changed during training. Second, we will visualize G’s output on the fixed_noise batch for every epoch. And third, we will look at a batch of real data next to a batch of fake data from G.
Loss versus training iteration
Below is a plot of D & G’s losses versus training iterations.

Visualization of G’s progression
Remember how we saved the generator’s output on the fixed_noise batch after every epoch of training. Now, we can visualize the training progression of G with an animation. Press the play button to start the animation.
fig = plt.figure(figsize=(8,8))
plt.axis("off")
ims = [[plt.imshow(np.transpose(i,(1,2,0)), animated=True)] for i in img_list]
ani = animation.ArtistAnimation(fig, ims, interval=1000, repeat_delay=1000, blit=True)
HTML(ani.to_jshtml())
